package com.szxy.frontend.order.service.impl;

import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.szxy.frontend.order.feigin.CommonRedisFeignClient;
import com.szxy.frontend.order.feigin.FrontendCartFeignClient;
import com.szxy.frontend.order.service.OrderService;
import com.szxy.mapper.TbOrderItemMapper;
import com.szxy.mapper.TbOrderMapper;
import com.szxy.mapper.TbOrderShippingMapper;
import com.szxy.pojo.TbOrder;
import com.szxy.pojo.TbOrderItem;
import com.szxy.pojo.TbOrderShipping;
import com.szxy.utils.IDUtils;
import com.szxy.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Auther:zwer
 * @Date:2019/9/26 10:56
 * @Description:com.szxy.frontend.order.service.impl
 * @Version:1.0
 **/
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private CommonRedisFeignClient commonRedisFeignClient;
    @Autowired
    private FrontendCartFeignClient frontendCartFeignClient;
    @Autowired
    private TbOrderItemMapper orderItemMapper;
    @Autowired
    private TbOrderMapper orderMapper;
    @Autowired
    private TbOrderShippingMapper orderShippingMapper;

    @Override
    @LcnTransaction
    public Result insertOrder(List<TbOrderItem> orderItemList, TbOrder tbOrder, TbOrderShipping tbOrderShipping) {
        // 获取订单号
        Long orderId = this.commonRedisFeignClient.selectOrderId();
        // 获取当前时间
        Date date = new Date();
        // 补齐订单数据
        tbOrder.setOrderId(orderId.toString());
        // 状态：1、未付款，2、已付款，3、未发货，4、已发货，5、交易成功，6、交易关闭
        tbOrder.setStatus(1);
        tbOrder.setCreateTime(date);
        tbOrder.setUpdateTime(date);
        // 买家是否已经评价 0 表示未评价 1 表示评价
        tbOrder.setBuyerRate(0);
        // 将订单插入数据库中
        this.orderMapper.insert(tbOrder);

        // 补齐订单商品数据
        for (TbOrderItem tbOrderItem : orderItemList) {
            // 生成 Id
            Long id = IDUtils.genItemId();
            tbOrderItem.setId(id.toString());
            tbOrderItem.setOrderId(orderId.toString());
            // 插入到数据库中
            orderItemMapper.insert(tbOrderItem);

            //删除购物车中对应的商品
            this.frontendCartFeignClient
                    .deleteItemFromCart(tbOrder.getUserId().toString(),Long.parseLong(tbOrderItem.getItemId()));
        }

        // 补齐订单地址数据
        tbOrderShipping.setOrderId(orderId.toString());
        tbOrderShipping.setCreated(date);
        tbOrderShipping.setUpdated(date);
        // 插入到数据库中
        this.orderShippingMapper.insert(tbOrderShipping);

        return Result.ok(orderId);
    }
}
